package com.senseuni.da.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.os.*
import android.telephony.TelephonyManager
import android.util.DisplayMetrics
import android.view.WindowManager
import com.elvishew.xlog.XLog
import com.senseuni.da.BuildConfig
import com.senseuni.da.MyApplication
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.util.HashMap

object PropertyUtil {

    fun createDeviceBasic() : HashMap<String, Any> {
        val params = HashMap<String, Any>()
        params["sn"] = Build.SERIAL
        params["model"] = Build.MODEL
        params["version"] = BuildConfig.VERSION_NAME
        params["version_code"] = BuildConfig.VERSION_CODE
        params["cpuid"] = MyApplication.DEVICE_ID
        params["android_version"] = Build.VERSION.RELEASE
        return params
    }

    fun createCMBasic(context: Context): HashMap<String, Any?> {
        val params = HashMap<String, Any?>()
        var imei:String? = null
        var imsi:String? = null
        var iccid:String? = null
        var cmVersion:String? = null
        var cmModel:String? = null
        try {
            val telephonyManager = context
                .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            imei = telephonyManager.imei
            imsi = telephonyManager.subscriberId
            iccid = telephonyManager.simSerialNumber
        } catch (e: Exception) {
            XLog.e("get cm basic fail:%s", e.message)
//            e.printStackTrace()
        }
        params["imei"] = imei
        params["imsi"] = imsi
        params["iccid"] = iccid
        params["cm_version"] = cmVersion
        params["cm_model"] = cmModel
        return params
    }

    fun createSignal(): HashMap<String, Any> {
        val params = HashMap<String, Any>()
        params["rssi"] = 0
        params["rsrp"] = 0
        params["rsrq"] = 0
        params["rssnr"] = 0
        return params
    }

    fun createSystemInfo(context: Context): HashMap<String, Any> {
        val params = HashMap<String, Any>()
        //可用内存(KB)
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo)
        val avaiMem = memoryInfo.availMem / 1024.0f
        params["mem"] = avaiMem.toInt()
        //可用存储(KB)

        //磁盘信息
        // 获取StorageManager实例
        val statFs = StatFs(Environment.getExternalStorageDirectory().path)
        val avaStorage = statFs.availableBytes / 1024.0f
        params["disk"] = avaStorage.toInt()
        val batteryStatus = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
        val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
        val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
        val isCharging =
            status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
        val batteryPercentage = (level / scale.toFloat() * 100).toInt()
        //battery
        params["battery"] = batteryPercentage
        //供电状态 1:市电 0：电池
        params["power"] = if(isCharging) 1 else 0
        //累计开机次数
        params["start_total"] = AppUtils.getBootTimes()
        //本次开机设备运行时间(s)
        params["device_run_time"] = SystemClock.uptimeMillis() / 1000
        //cpu占用情况（%）
        var cpuUsage = 0.0f
        var reader:BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/stat"))
            val cpuStats = reader.readLine().split(" ")

            val userTime = cpuStats[2].toLong()
            val niceTime = cpuStats[3].toLong()
            val systemTime = cpuStats[4].toLong()
            val idleTime = cpuStats[5].toLong()
            val iowaitTime = cpuStats[6].toLong()
            val irqTime = cpuStats[7].toLong()
            val softirqTime = cpuStats[8].toLong()

            // 计算总的时间
            val totalTime = userTime + niceTime + systemTime + idleTime + iowaitTime + irqTime + softirqTime
            // 计算活动时间
            val activeTime = userTime + niceTime + systemTime + irqTime + softirqTime
            // 计算 CPU 占用率
            cpuUsage = (activeTime.toFloat() / totalTime.toFloat()) * 100
        } catch (e: IOException) {
//            e.printStackTrace()
            XLog.e("get cpu info error:${e.message}")
        } finally {
            try {
                reader?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        params["cpu_usage"] =  cpuUsage.toInt()
        return params
    }

    //音量改变时
    fun createVolumeProp(context: Context): Int {
        val audioManager =
            context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val systemVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        return AppUtils.systemVolumeTo(systemVolume)
    }

    fun createDisplayProp(context: Context) : HashMap<String, Any> {
        val params = HashMap<String, Any>()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        params["resolution_width"] = displayMetrics.widthPixels
        params["resolution_height"] = displayMetrics.heightPixels
        params["screen_size"] = 10.1
        return params
    }
}